package tau.dimes.web;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tau.dimes.beans.LoginBean;

/**
 * Servlet implementation class FilesServlet
 */
public class FilesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FilesServlet() {
        super();
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
    	IOException
    {
    	LoginBean login = (LoginBean)request.getSession().getAttribute("login");
    	String action = request.getParameter("action");
    	if (action != null && !(action.length() == 0))
    	{
    		if ("downloadUserFile".equalsIgnoreCase(action))
    			doDownloadUserFile(request, response, login);
    		
    		return;
    	}
		response.sendError(500, "Unknown action");
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	private void doDownloadUserFile(HttpServletRequest request, HttpServletResponse response,
		LoginBean login) throws IOException
	{
		String filename = request.getParameter("filename");
		if (filename == null || filename.equals(""))
		{
			response.sendError(404);
			return;
		}
		
		UserFiles userFiles = new UserFiles(login.getUsername(), getServletContext());
		
		InputStream is = null;
		try
		{
			is = new FileInputStream(userFiles.getFile(filename));
		}
		catch (FileNotFoundException e)
		{
			response.sendError(404);
			return;
		}
		
		if (filename.toLowerCase().endsWith(".trace.xml"))
			response.setContentType("text/xml");
		
		if (filename.toLowerCase().endsWith(".query.xml"))
			response.setContentType("text/xml");
		
		response.setHeader("content-disposition", "attachment; filename=\"" + filename + "\"");
		int bufferSize = response.getBufferSize();
		byte[] buffer = new byte[bufferSize];
		int read;
		while ((read = is.read(buffer, 0, bufferSize)) > 0)
		{
			response.getOutputStream().write(buffer, 0, read);
		}
		
		is.close();
	}
}
